package com.happle.gcmclient;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.happle.gcmclient.adapter.ConversionAdapter;
import com.happle.gcmclient.backendmanager.task.DeleteConversationTask;
import com.happle.gcmclient.backendmanager.task.UpdateConversationTask;
import com.happle.gcmclient.config.Constants;
import com.happle.gcmclient.config.GlobalValue;
import com.happle.gcmclient.managers.MessagesManager;
import com.happle.gcmclient.obj.ConversationObj;
import com.happle.gcmclient.obj.MessageObj;

public class ConversationActivity extends BaseActivity {

	public static final String TAG = "ConversationActivity";
	private IntentFilter messageFilter;
	private GCMReceiver gcmMessageReceier;
	protected UpdateConversationTask updTask;
	protected DeleteConversationTask delTask;
	private ListView lsvConversation;
	private ArrayList<ConversationObj> listConversation;
	private ConversionAdapter conversationAdapter;
	private MessagesManager msgManager;
	private ConversationObj clicked_conversation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.conversation_listview);
		initUI();
		updateConversationsList();
		initReceiver();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		reloadLanguge();
		registerReceiver(gcmMessageReceier, messageFilter);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.d("CONVESATION", "onPause");
		super.onPause();
		unregisterReceiver(gcmMessageReceier);
	}

	private void initUI() {
		initHeader();
		setHeaderTitle(getString(R.string.titleConversationsActivity), Constants.TITLE_CONVERSATION_IMAGE_NUM);
		lsvConversation = (ListView) findViewById(R.id.lsvConversation);
		registerForContextMenu(lsvConversation);
	}

	private void initData() {
		if (msgManager == null) {
			msgManager = new MessagesManager(self);
		}
		listConversation = msgManager.getAllConversations();
	}

	private void bindDataToList() {
		conversationAdapter = new ConversionAdapter(self, listConversation);
		lsvConversation.setAdapter(conversationAdapter);
		lsvConversation.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
                // check if a clicked conversation has new messages
                if (listConversation.get(arg2).is_has_new_messages()){
				    // read messages in conversation by click
                    if (msgManager == null)
                        msgManager = new MessagesManager(self);
                    msgManager.readNewMessages(listConversation
                        .get(arg2).get_wave_id());
                }
                // send extras and start MessageListActivity
				Intent i = new Intent(self, MessageListActivity.class);
				Intent intent = i.putExtra(Constants.WAVE_ID, listConversation
						.get(arg2).get_wave_id());
				i.putExtra(Constants.lng_id_p, listConversation.get(arg2)
						.get_lng_id());
				i.putExtra(Constants.FIELD_REQUEST_CODE,
						String.valueOf(Constants.REQUEST_CODE_UPD));
				i.putExtra(Constants.PUSH_FROM_CONVERSATION, true);
				startActivityForResult(i, 10);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (data.getExtras().containsKey(
					Constants.FIELD_NEED_UPADATE_LIST_CONVERSATION)) {
				showToastMessage(R.string.UpdateListConversation);
				// Reload data and update list if need
				updateConversationsList();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

		int position = info.position;
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		if (listConversation.get(position).is_conv_status()) {
			inflater.inflate(R.menu.activity_conversation, menu);
		} else {
			inflater.inflate(R.menu.activity_conversation_limited, menu);
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		int taskResult = -1;
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		clicked_conversation = (ConversationObj) listConversation
				.get(info.position);
		if (msgManager == null)
			msgManager = new MessagesManager(self);
		switch (item.getItemId()) {
		case R.id.menu_contx_close_conversation:
			taskResult = msgManager.closeConversation(clicked_conversation
					.get_wave_id());
			taskResult = updateConversation(clicked_conversation,
					Constants.MSG_STATUS_CLOSED, GlobalValue.registerId);
			updateConversationsList();
			return true;
		case R.id.menu_contx_delete_conversation:
			taskResult = msgManager.deleteConversation(clicked_conversation
					.get_wave_id());
			taskResult = deleteConversation(clicked_conversation,
					GlobalValue.registerId);
			updateConversationsList();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	public void updateConversationsList() {
		initData();
		bindDataToList();
	}

	private int updateConversation(ConversationObj convObj, int conv_status,
			String registration_id) {
		int taskResult = -1;
		try {
			updTask = new UpdateConversationTask(convObj, conv_status,
					registration_id, self);
			updTask.execute();
			taskResult = updTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return taskResult;
	}

	private int deleteConversation(ConversationObj convObj,
			String registration_id) {
		int taskResult = -1;
		try {
			delTask = new DeleteConversationTask(convObj, registration_id, self);
			delTask.execute();
			taskResult = delTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return taskResult;
	}

	// broadcast receiver - to test and if there is no alternative
	private void initReceiver() {
		gcmMessageReceier = new GCMReceiver();
		messageFilter = new IntentFilter();
		messageFilter.addAction(Constants.ACTION_ON_NEW_MESSAGE);
	}

	private class GCMReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.d("CONVESATIONS", "Receive new messsage 2");
			MessageObj addMsg = (MessageObj) intent
					.getParcelableExtra(Constants.KEY_MESSAGE_OBJECT);
			if (addMsg != null) {
				for (ConversationObj obj : listConversation) {
					// Exist conversation , update the number message
					if (obj.get_wave_id().equals(addMsg.get_wave_id())) {
						if (addMsg.is_msg_status())
							obj.set_msgs_count(obj.get_msgs_count() + 1);
						else
							obj.set_msg_status(addMsg.is_msg_status());
						conversationAdapter.notifyDataSetChanged();
						break;
					}
					else
				    // New conversation, reload list
					{
						updateConversationsList();
					}
				}
			}
		}
	};


	private void reloadLanguge() {

		setHeaderTitle(getString(R.string.titleConversationsActivity), Constants.TITLE_CONVERSATION_IMAGE_NUM);
		updateStatusTitle();

	}
}
